import os

from .script_processor import ScriptProcessor  # 如果需要在模块间相互引用

class ScriptPack:
    def __init__(self, filename, line_creator):
        self.input_file = filename
        self.output_file = os.path.splitext(self.input_file)[0] + '_processed.xml'
        self.line_creator = line_creator
        self.commands = []
        self.read_procesor()

    def read_procesor(self):
        """解析文件内容"""
        with open(self.input_file, 'r', encoding='utf-8') as file:
            content = file.read()
            current_pos = 0
            content_length = len(content)

            while current_pos < content_length:
                # 1. 查找下一个Command开始标记
                start_tag_pos = content.find("[Command", current_pos)
                if start_tag_pos == -1:
                    break  # 没有找到更多Command

                # 2. 查找Command结束标记
                end_tag_pos = content.find("[/Command]", start_tag_pos)
                if end_tag_pos == -1:
                    raise ValueError("未找到匹配的[/Command]标签")

                # 3. 查找下一个Command开始位置（当前段的结束位置）
                next_command_pos = content.find("[Command", end_tag_pos + 1)
                if next_command_pos == -1:
                    next_command_pos = content_length  # 最后一段

                # 4. 提取整个Command段（从[Command到下一个[Command之前）
                next_command_start = end_tag_pos + len("[/Command]")

                command_block = content[next_command_start:next_command_pos].strip()
                header_block = content[start_tag_pos:end_tag_pos].strip()


                # 6. 提取ID和名称
                id_start = header_block.find('Id="') + 4
                id_end = header_block.find('"', id_start)
                if id_start == -1 or id_end == -1:
                    raise ValueError("Command ID格式错误")

                command_id = int(header_block[id_start:id_end])
                command_name = header_block.split("]", 1)[1].strip()

                processor = ScriptProcessor(command_block, self.line_creator, True)
                processor.command_id = command_id
                processor.command_name = command_name
                processor.xml_indent += 1
                self.commands.append(processor)

                # 9. 移动当前位置到下一个Command开始处
                current_pos = next_command_pos

    def process(self):
      for command in self.commands:
        command.process()
      pass

    def save(self):
        with open(self.output_file, 'w', encoding='utf-8') as f_out:
            f_out.write('<?xml version="1.0" encoding="UTF-8"?>\n<Script>\n')
            for command in self.commands:
                f_out.write(f'    <Command Id="{command.command_id}" Name="{command.command_name}">\n')
                command.write_to(f_out)
                f_out.write(f'    </Command>\n')
            f_out.write('</Script>')



